<?php
//error_reporting(E_ALL);
error_reporting(E_ALL ^ E_WARNING);
ini_set('display_errors','On');

function busca_remplaza($txt, $inicio, $fin, $r_ini = '', $r_fin = '', $exp_reg = false){
  $offset = 0;
  while( strpos($txt,$inicio,$offset) || preg_match($inicio, $txt, $coincide, PREG_OFFSET_CAPTURE, $offset) ) {
    $buscar  = array($inicio, $fin, "\n"); // texto que quiero quitar de $encontardo
    $cambiar = ""; 

    if($exp_reg) preg_match($inicio, $txt, $coincide, PREG_OFFSET_CAPTURE, $offset);

    $pos1 = $exp_reg ? $coincide[0][1] : strpos($txt,$inicio,$offset);
    $pos2 = strpos($txt,$fin,$pos1);
    $offset = $pos1+1;
    
    $encontado = trim(substr($txt, $pos1, $pos2-$pos1));
    $por_remplazar = str_replace($buscar, $cambiar, $encontado);
    if($exp_reg) $por_remplazar = preg_replace($inicio, "", $por_remplazar);
    $por_remplazar = $r_ini.trim($por_remplazar).$r_fin;
    $txt = substr_replace ( $txt, $por_remplazar, $pos1, $pos2-$pos1 );
    //$matriz[] = array( $encontado, $por_remplazar);
  }
  return $txt;
  //print_r($matriz);
}

// busqueda simple
$buscar    = array(
    "\\seite",
    "\\comi ",
    "\\ni",
    "\\=",
    "\\input",
    "\\titletrue",
    "\\pageno",
    "\\numcap",
    "\\chapter",
    "\\san",
    "{\\label ",
    "\\label",
    "\\onehalf",
    "\\ts",
    "\\cr",
    "\\overfullrule",
    "\\cleantrue",
    "\\>",
    "\\bigl",
    "\\bigr",
    "\\link",
    "\\inti ",
    "\\exi "
);
$remplazar = array(
    "",
    "``",
    "\\noindent",
    "=",
    "%\\input",
    "%\\titletrue",
    "%\\pageno",
    "%\\numcap",
    "\\chapter{}",
    "",
    "\\textsf{",
    "",
    "\\frac12",
    "",
    "\\\\",
    "%\\overfullrule",
    "%\\cleantrue",
    "",
    "\\left",
    "\\right",
    "\\noindent\\parbox[t]{3in}\n",
    "¿",
    "¡"
);

// Busqueda con expresiones regulares
$reg_buscar    = array(
    "/\\\\sec \d{1,2}\. (.*)/",
    "/\{([^\}]*)\\\\over([^\}]*)\}/",
    "/\\\\eqalign(.*?)\n{2}/s",
    "/\\\\esn(.*?)\n{2}/s",
    "/\\\\enmarca(.*?)\n{2}/s",
    "/\\\\line(.*?)\n{2}/s",
    "/\\\\e\s*\d{1,2}(.*?)\n{2}/s",
    "/\\\\e\s+(.*?)\n{2}/s",
    "/\\\\ecmarco(.*?)\n{2}/s",
    );
$reg_remplazar = array(
    "\\section{ $1 }",
    "\\frac{ $1 }{ $2 }",
    "\\begin{align*}\n$1\n\\end{align*}\n\n",
    "\\begin{align*}\n$1\n\\end{align*}\n\n",
    "\\begin{align*}\n\\framebox{ $1}\n\\end{align*}\n\n",
    "\\begin{align*}\n$1\n\\end{align*}\n\n",
    "\\begin{align}\n$1\n\\end{align}\n\n",
    "\\begin{align*}\n$1\n\\end{align*}\n\n",
    "\\begin{align}\n\\framebox{ $1}\n\\end{align}\n\n",
    );

$texto = utf8_decode(file_get_contents($argv[1]));

$texto = str_replace($buscar,$remplazar,$texto);
$texto = preg_replace($reg_buscar, $reg_remplazar, $texto);

/*preg_match_all("/\\\\link\{((?(?>[^{}]+)|(?R))*)\}/uisx",$texto,$salida);/**/
preg_match_all("/\\\\link\{((?(?>[^{}]+)|(?R))*?)\}/uisx",$texto,$salida);
print_r($salida);


file_put_contents("1_".$argv[1],utf8_encode($texto));

?>
